<!--
 @description 帮助中心 - 类目列表
 @fileName tableData.vue
 @author zengqiongying
 @created 2022/01/10 11:41:46
-->
<template>
  <div class="content-table-container">
    <div class="content-tree">
      <Tree ref="refTree" :no-request="tabIndex!==0" :classify-code="classifyCode" @get-tree="handleGetTree" @change="handleCateChange" />
    </div>
    <div class="content-table">
      <table-box
        ref="refTable"
        no-request
        :off-set="-10"
        :data="tableData"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaws"
        :selected-arry.sync="tableSelected"
        show-selection
        :show-custom-setting="false"
        :show-custom-combine="false"
        :show-custom-collect="false"
        :table-sortable="false"
        @selection-change="handleselectionChange"
        @btnOperate="btnOperate"
        @row-click="handleRowClick"
      />
    </div>

    <Move
      v-if="showMove"
      :visible.sync="showMove"
      :tree-data="treeData "
      :ids="bacthIds"
      @success="refreshTable"
    />
    <NumberDetail
      v-if="showNumDetail"
      :visible.sync="showNumDetail"
      :type="numDetailType"
      :content-title="activeRowData.title"
      :content-id="activeRowData.id"
    />
    <el-dialog
      ref="refAdd"
      v-el-drag-dialog
      title="新增"
      :visible.sync="showAddType"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      append-to-body
      @close="closeDialog"
    >
      <el-form ref="refForm" :model="formData" size="mini" label-width="80px">
        <el-form-item label="内容类型:" prop="contentType" :rules="[{required:true,message:'请选择内容类型',trigger:['change','blur']}]">
          <el-select v-model="formData.contentType" style="width:100%">
            <el-option :value="1" label="图文" />
            <el-option :value="2" label="视频" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="closeDialog">取消</el-button>
        <el-button size="mini" type="primary" @click="saveContentType">下一步</el-button>
      </div>
    </el-dialog>

    <!-- 导出 -->
    <export-files
      v-if="showExport"
      title="导出商品"
      :visible.sync="showExport"
      :config="exportConfig"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getDetail, deleteContent, updateContentState, updateContentSort } from '@/api/content'
import Tree from './components/Tree'
import NumberDetail from './components/NumberDetail'
import Move from './components/Move'
export default {
  name: 'HelpCategoryTable',
  components: { Tree, Move, NumberDetail },
  props: {
    classifyCode: {
      type: String,
      default: ''
    },
    classifyName: {
      type: String,
      default: ''
    },
    tabIndex: {
      type: Number,
      default: 0
    },
    buttons: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const that = this
    return {
      tableData: [],
      tableSelected: [],
      otherRaws: {},
      otherFilters: [], // [{ id: 'applyType', property: 'applyType', value: this.classifyCode, operator: '=' }],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/contentInfo/page`,
        // hideSearchBar: true,
        // onlySearchBar: true,
        tabIndex: 0,
        apiHeader: {
          'Permission-PerCode': 'content',
          'Permission-App': 'content-center'
        },
        setting: [
          {
            prop: 'title',
            label: '标题',
            minWidth: 200,
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetail
          },

          {
            prop: 'contentType',
            label: '类型',
            width: 100,
            type: 'select',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'content-center',
              dictTypeCode: 'CONTENT_TYPE'
            } // 1 图文，2 视频
          },
          {
            prop: 'sketch',
            label: '概述',
            minWidth: 200
          },
          {
            prop: 'coverUrl',
            label: '封面图',
            minWidth: 100,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              // const coverUrl = (row.covers && row.covers[0]) || ''
              const coverUrl = row.coverUrl || ''
              if (coverUrl) {
                const url = that.formatImageUrl(coverUrl)
                return (<div class='cate_img'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'state',
            label: '状态',
            width: 100,
            type: 'select',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'content-center',
              dictTypeCode: 'STATE'
            }
          },

          {
            prop: 'sort',
            label: '排序',
            minWidth: 200,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              if (this.isProduction) {
                const btns = []
                if (this.hasPermission('top')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 3)} class='btn-green my-txt-btn'>置顶</el-button>)
                }
                if (this.hasPermission('up')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 1)} class='btn-green my-txt-btn'>上移</el-button>)
                }
                if (this.hasPermission('down')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 2)} class='btn-green my-txt-btn'>下移</el-button>)
                }
                if (this.hasPermission('bottom')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 4)} class='btn-green my-txt-btn'>置底</el-button>)
                }
                return _h('div', btns)
              } else {
                return (<div>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 3)} class='btn-green my-txt-btn'>置顶</el-button>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 1)} class='btn-green my-txt-btn'>上移</el-button>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 2)} class='btn-green my-txt-btn'>下移</el-button>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 4)} class='btn-green my-txt-btn'>置底</el-button>
                </div>)
              }
            }
          },
          {
            prop: 'readNum',
            label: '浏览量',
            width: 120,
            sortable: false,
            type: 'hidden',
            render: (_h, row) => {
              return (
                <div class='btn-show-count'>
                  { row.readNum || 0 }
                  <div class='btn btn-green' onClick={that.handleNumberDetail.bind(this, row, 'read')}>
                    查看明细
                  </div>
                </div>
              )
            }
          },
          {
            prop: 'likeNum',
            label: '点赞量',
            width: 120,
            sortable: false,
            type: 'hidden',
            render: (_h, row) => {
              return (
                <div class='btn-show-count'>
                  { row.likeNum || 0 }
                  <div class='btn btn-green' onClick={that.handleNumberDetail.bind(this, row, 'like')}>
                    查看明细
                  </div>
                </div>
              )
            }
          },
          {
            prop: 'unLikeNum',
            label: '点踩量',
            width: 120,
            sortable: false,
            type: 'hidden',
            render: (_h, row) => {
              return (
                <div class='btn-show-count'>
                  { row.unLikeNum || 0 }
                  <div class='btn btn-green' onClick={that.handleNumberDetail.bind(this, row, 'unlike')}>
                    查看明细
                  </div>
                </div>
              )
            }
          },
          {
            prop: 'collectNum',
            label: '收藏量',
            width: 120,
            sortable: false,
            type: 'hidden',
            render: (_h, row) => {
              return (
                <div class='btn-show-count'>
                  { row.collectNum || 0 }
                  <div class='btn btn-green' onClick={that.handleNumberDetail.bind(this, row, 'collect')}>
                    查看明细
                  </div>
                </div>
              )
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 150,
            type: 'date',
            formatData: ({ createTime }) => {
              return parseTime(createTime)
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            minWidth: 150,
            type: 'date',
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime)
            }
          }
        ],
        btnList: !this.isProduction ? [
          {
            buttonName: '新增',
            optCode: 'add',
            outerFlag: true
          },
          {
            buttonName: '编辑',
            optCode: 'edit',
            outerFlag: true
          },
          {
            buttonName: '移动',
            optCode: 'move',
            outerFlag: true
          },
          {
            buttonName: '删除',
            optCode: 'del',
            outerFlag: true
          },
          {
            buttonName: '启用',
            optCode: 'enable',
            outerFlag: true
          },
          {
            buttonName: '停用',
            optCode: 'disable',
            outerFlag: true
          },
          {
            buttonName: '导出',
            optCode: 'export',
            outerFlag: true
          }] : null
      },
      treeData: [], // 类目树
      selectedCate: '', // 当前所选类目
      sortTime: null, // 排序操作时间判断
      sorting: false, // 是否正在操作排序
      activeRowData: '',
      showMove: false,
      showAddType: false,
      formData: {
        contentType: 1
      },
      showNumDetail: false,
      numDetailType: '', // 数据统计明细类型： collect 收藏 / read  预览 / linke 点赞 / unlike 点踩
      showExport: false,
      exportConfig: [
        {
          code: 'content_export', // 导出编码，前段定义，同一个config中code不能重复
          name: '导出内容', // 导出名称，如：商品导出，导出用户
          async: false, // 是否异步
          templateCode: '', // 模板code，若需要则由后端提供
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/contentInfo/export`, // 导出数据的接口地址
          templateApi: ``, // 模板导出接口
          templateMethod: 'post',
          filtersRaw: [], // filter查询参数
          paramsRaw: {}, // params查询参数
          selectedRows: [], // 当前所选中的数据行
          queryField: 'id'// 指定行导出的字段名称
        }
      ]
    }
  },
  computed: {
    // 多选ID
    bacthIds() {
      return this.tableSelected.map(v => v.id)
    },
    // 当前所选类目Id
    categoryId() {
      return (this.selectedCate && this.selectedCate.id) || ''
    },
    // 当前所选类目名称
    categoryName() {
      return (this.selectedCate && this.selectedCate.categoryName) || ''
    }
  },
  created() {
    this.tableConfig.tabIndex = this.tabIndex
  },
  methods: {
    hasPermission(code) {
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    handleGetTree(data) {
      this.treeData = data
    },
    handleselectionChange(val) {
      this.tableSelected = val
    },
    handleRowClick({ row }) {
      this.$refs.refTable.clearSelection()
      this.$nextTick(() => {
        this.$refs.refTable.toggleRowSelection(row, true)
        this.activeRowData = row || ''
      })
    },
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'del':
          if (!this.singleJudge(this.tableSelected, '删除', true)) {
            return
          }
          this.handleDelete(this.tableSelected[0])
          break
        case 'disable':
          if (!this.singleJudge(this.tableSelected, '停用', false)) {
            return
          }
          this.handleChangeStatus(0) // state 1：启用  0：停用
          break
        case 'enable':
          if (!this.singleJudge(this.tableSelected, '启用', false)) {
            return
          }
          this.handleChangeStatus(1) // state 1：启用  0：停用
          break
        case 'move':
          if (!this.singleJudge(this.tableSelected, '移动', false)) {
            return
          }
          if (this.bacthIds.length === 0) {
            this.$message({
              message: '请选择需要移动的内容',
              type: 'warning'
            })
          }
          this.$nextTick(() => {
            this.showMove = true
          })
          break
        case 'export':
          this.handleExport()
          break
        default :
          break
      }
    },
    handleCateChange(data) {
      this.selectedCate = data || ''
      this.searchTableData(true)
    },
    refreshTree() {
      this.$refs.refTree.getTree()
    },
    searchTableData(flag) {
      if (this.categoryId && this.categoryId !== 'all') {
        this.otherFilters = [
          { id: 'categoryId', property: 'categoryId', value: this.categoryId, operator: '=' }
        ]
      } else {
        this.otherFilters = [
          { id: 'classifyCode', property: 'classifyCode', value: this.classifyCode, operator: '=' }
        ]
      }
      this.$nextTick(() => {
        this.refreshTable(flag)
      })
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
    },
    resetLayout() {
      this.$refs.refTable.resetLayout()
    },
    // 查看详情
    handleDetail(row) {
      if (!row.id) {
        this.$message.warning('数据异常')
        return
      }
      if (this.loading) return
      this.loading = true
      getDetail(row.id).then(res => {
        this.loading = false
        if (res.data && res.data.id) {
          if (!res.data.categoryName) {
            res.data.categoryName = this.categoryName
          }
          this.$emit('detail', res.data)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 查询数据统计明细
    handleNumberDetail(row, type) {
      if (!row.id) {
        this.$message.warning('数据异常')
        return
      }
      this.numDetailType = type
      this.activeRowData = row
      this.$nextTick(() => {
        this.showNumDetail = true
      })
    },
    // 编辑/新增
    handleEdit(row) {
      if (!row) {
        if (!this.categoryId || this.categoryId === 'all') {
          this.$message({
            message: '请选择末级目录进行新增',
            type: 'warning'
          })
          return
        }
        if (this.selectedCate.lastStage !== 1) {
          this.$message({
            message: '该类目不是末级类目，不能添加内容',
            type: 'warning'
          })
          return
        }
        this.$nextTick(() => {
          this.showAddType = true
        })
        return
      }
      if (this.loading) return
      this.loading = true
      getDetail(row.id).then(res => {
        this.loading = false
        if (res.data && res.data.id) {
          const row = res.data
          const contentType = res.data.contentType
          this.$nextTick(() => {
            this.$emit('edit', {
              category: this.selectedCate,
              contentType,
              row
            })
          })
        }
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 处理启用/停用
     * @param {Number} state 1 启用 0 停用
     * @param {String} id
    */
    handleChangeStatus(state) {
      const tmpArr = this.tableSelected.filter(row => row.state === state)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选内容包含${state ? '启用' : '停用'}状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选内容${state ? '启用' : '停用'},是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedIds = this.tableSelected.map(v => v.id)
        const params = { ids: selectedIds, state }
        updateContentState(params).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '操作成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      })
    },
    // 删除处理
    handleDelete() {
      /* const tmpArr = this.tableSelected.filter(row => row.state === 1)
      if (tmpArr.length > 0) {
        this.$message.warning('只能删除状态为停用的内容')
        return
      } */
      this.$confirm('此操作将永久删除当前所选内容, 将导致相关数据丢失，是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.tableSelected[0].id
        deleteContent(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型： 1 上移 ， 2 下移 ，3置顶， 4 置底
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updateContentSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    },
    closeDialog() {
      this.formData = {
        contentType: 1
      }
      this.$refs.refForm.clearValidate()
      this.showAddType = false
    },
    saveContentType() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const contentType = this.formData.contentType
          this.showAddType = false
          this.$nextTick(() => {
            this.$emit('edit', { category: this.selectedCate, contentType })
          })
        }
      })
    },
    refreshTableHeight() {
      this.$refs.refTable.refreshTableHeight()
    },
    // 导出
    handleExport() {
      let filtersRaw = this.otherFilters
      const allFilters = this.$refs.refTable.getAllFilters()

      if (allFilters.searchBarFilter) {
        filtersRaw = [...filtersRaw, ...allFilters.searchBarFilter]
      }
      if (allFilters.combineFilter) {
        filtersRaw = [...filtersRaw, ...allFilters.combineFilter]
      }
      const exportConfig = this.exportConfig[0]
      exportConfig.filtersRaw = filtersRaw
      exportConfig.selectedRows = this.tableSelected || []
      this.$set(this.exportConfig, 0, exportConfig)
      this.$nextTick(() => {
        this.showExport = true
      })
    }
  }
}

</script>
<style lang='scss' scoped>
  .my-txt-btn{
    padding: 0 !important;
  }
  .content-table-container{
    position: relative;
    height: 100%;
    display: flex;
    .content-tree{
      position: relative;
      height: 100%;
      padding-top: 5px;
      width: 300px;
      border: 1px solid #ddd;
      margin-right: 10px;
      overflow: auto;
      box-sizing: border-box;
    }
    .content-table{
      flex: 1;
      overflow: hidden;
    }

    .btn-show-count{
      display: flex;
      align-items: center;
      .btn{
        display: none;
        margin-left: 10px;
      }
    }
    /deep/ .table-list-box{
      tr:hover{
        .btn-show-count .btn{
          display: block;
        }
      }
    }
  }
  .cate_img{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      width: 70px;
      height: 70px;
      // object-fit: cover;
      object-fit: contain;
    }
  }
</style>
